package com.common.app.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.Selection
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.LinearLayout.HORIZONTAL
import android.widget.LinearLayout.VERTICAL
import android.widget.RelativeLayout
import com.common.app.R
import com.common.app.databinding.ViewNumberChangeRoundBinding
import com.common.app.utls.Utils.px2sp
import com.common.base.app.extras.dpDimenPx
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.yes

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：29/8/2023
 *
 * 描述：数字加减控件
 *
 * 修订历史：
 *
 */
class CusNumberView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr), TextWatcher, View.OnClickListener {

    private val binding: ViewNumberChangeRoundBinding by lazy {
        ViewNumberChangeRoundBinding.inflate(
            LayoutInflater.from(context),
            this,
            true
        )
    }

    private var max = 999
    private var min = 1
    private var enable = true
    private var listener: OnNumberChangeListener? = null

    private var orientationType = 1//默认横向
    private var mImageWidth = dpDimenPx(R.dimen.dp_25).toInt()
    private var mImageHeight = dpDimenPx(R.dimen.dp_25).toInt()
    private var mSubImage: Drawable? = null
    private var mAddImage: Drawable? = null

    private var mTextSize = 14
    private var textColor = -1
    private var typeface = 0

     val number: Int
        get() {
            val str = binding.numberChangeEdit.text.toString()
            if (TextUtils.isEmpty(str)) {
                binding.numberChangeEdit.setText(min.toString())
                return min
            }
            return str.toInt()
        }

    init {
        if (attrs != null) {
            initAttrs(context, attrs)
        }
        initView()
    }

    fun setOnNumberChangeListener(lis: OnNumberChangeListener?) {
        listener = lis
    }

    private fun initAttrs(context: Context, attributeSet: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CusNumberView)
        orientationType =
            typedArray.getInt(R.styleable.CusNumberView_viewOrientation, orientationType)

        mImageWidth =
            typedArray.getDimensionPixelSize(R.styleable.CusNumberView_viewImageWidth, mImageWidth)
        mImageHeight = typedArray.getDimensionPixelSize(
            R.styleable.CusNumberView_viewImageHeight,
            mImageHeight
        )
        mSubImage = typedArray.getDrawable(R.styleable.CusNumberView_viewSubImage)
        mAddImage = typedArray.getDrawable(R.styleable.CusNumberView_viewAddImage)

        textColor = typedArray.getColor(R.styleable.CusNumberView_viewTextColor, Color.BLACK)
        if (typedArray.hasValue(R.styleable.CusNumberView_viewTextSize)) {
            mTextSize =
                typedArray.getDimension(R.styleable.CusNumberView_viewTextSize, mTextSize.toFloat())
                    .toInt()
            mTextSize = px2sp(context, mTextSize.toFloat())
        }
        typeface = typedArray.getInt(R.styleable.CusNumberView_viewTextStyle, typeface)
        typedArray.recycle()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        binding.numberChangeEdit.clearFocus()
        binding.numberChangeEdit.isEnabled = false
        binding.numberChangeEdit.addTextChangedListener(this)
        binding.numberChangeEdit.setText(min.toString())

        (orientationType == 0).yes {
            binding.numberTotalLl.orientation = VERTICAL
        }.otherwise {
            binding.numberTotalLl.orientation = HORIZONTAL
        }
        binding.numberChangeEdit.setTextColor(textColor)

        (typeface == 0).yes {
            binding.numberChangeEdit.typeface = Typeface.DEFAULT
        }.otherwise {
            binding.numberChangeEdit.typeface = Typeface.DEFAULT_BOLD
        }

        binding.numberChangeMinusImg.layoutParams = LayoutParams(mImageWidth, mImageHeight)
        binding.numberChangeAddImg.layoutParams = LayoutParams(mImageWidth, mImageHeight)

        if (mSubImage != null) {
            binding.numberChangeMinusImg.background = mSubImage
        }
        if (mAddImage != null) {
            binding.numberChangeAddImg.background = mAddImage
        }

        binding.numberChangeMinusBtn.setOnClickListener(onClick = this)
        binding.numberChangeAddBtn.setOnClickListener(onClick = this)
    }


    override fun onClick(v: View) {
        if (!enable) {
//            PToastUtils.t(App.getContext(), "库存不足！")
            return
        }
        var num = number
        val oldNum = num
        when (v.id) {
            R.id.number_change_minus_btn -> if (num > min) {
                num--
                binding.numberChangeEdit.setText(num.toString())
            }

            R.id.number_change_add_btn -> if (num < max) {
                num++
                binding.numberChangeEdit.setText(num.toString())
            }
        }
        if (listener != null && oldNum != num) {
            listener?.OnNumberChange(this, num, num - oldNum)
        }
    }

    fun setEnable(enable: Boolean) {
        this.enable = enable
    }

    fun setMax(max: Int) {
        if (max < min) {
            return
        }
        this.max = max
    }

    fun setMin(min: Int) {
        if (min < max) {
            return
        }
        this.min = min
    }

    fun setCurNum(value: String) {
        binding.numberChangeEdit.setText(value)
    }

    private fun checkNum() {
        var num = binding.numberChangeEdit.text.toString().toInt()
        if (num > max) {
            num = max
            binding.numberChangeEdit.setText(num.toString())
        } else if (num < min) {
            num = min
            binding.numberChangeEdit.setText(num.toString())
        }
        binding.numberChangeEdit.apply {
            val editable = text
            //新字符串的长度
            val newLen = length()
            //设置新光标所在的位置
            Selection.setSelection(editable, newLen)
        }

        checkBtnStatus()
    }

    override fun beforeTextChanged(
        s: CharSequence, start: Int, count: Int,
        after: Int
    ) {
    }

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        checkNum()
    }

    override fun afterTextChanged(s: Editable) {}
    interface OnNumberChangeListener {
        fun OnNumberChange(view: CusNumberView?, number: Int, offset: Int)
    }

    fun getTotalView(): LinearLayout {
        return binding.numberTotalLl
    }

    private fun checkBtnStatus() {
        if (binding.numberChangeEdit.text.toString().toInt() <= min) {
            // number小于等于min时的处理
            binding.numberChangeMinusBtn.isEnabled = false
            binding.numberChangeMinusImg.alpha = 0.3f
            binding.numberChangeAddBtn.isEnabled = true
            binding.numberChangeAddImg.alpha = 1f

        } else if (binding.numberChangeEdit.text.toString().toInt() >= max) {
            // number大于等于max时的处理
            binding.numberChangeMinusBtn.isEnabled = true
            binding.numberChangeMinusImg.alpha = 1f
            binding.numberChangeAddBtn.isEnabled = false
            binding.numberChangeAddImg.alpha = 0.3f
        } else {
            // number在min和max之间时的处理
            binding.numberChangeMinusBtn.isEnabled = true
            binding.numberChangeMinusImg.alpha = 1f
            binding.numberChangeAddBtn.isEnabled = true
            binding.numberChangeAddImg.alpha = 1f
        }
    }

}
